﻿using DevExpress.LookAndFeel;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Docking;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraNavBar;
using DevExpress.XtraTab.ViewInfo;
using DevExpress.XtraTabbedMdi;
using DevMy.Model;
using DevMy.PublicClass;
using DevMy.PublicSetUp;
using DevMy.Vou;
using MDIDemo;
using MDIDemo.Model;
using MDIDemo.PublicClass;
using MDIDemo.vou;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevMy
{
    public partial class Form_NewMain : DevExpress.XtraBars.Ribbon.RibbonForm, IoSocketClient
    {
        public Form_NewMain(string Version, string SkinName)
        {
            InitializeComponent();
            this.Version = Version;
            Ini(SkinName);
            //CreateColorPopup(popupControlContainer1);
            InitSkinGallery();
            InitTabbedMDI();
            //InitFontGallery();
            //InitColorGallery();
            //InitEditors();
            //InitSchemeCombo();
            //InitPrint();
        }
        private string ip = "192.168.3.8";
        private int port = 50000;
        private TcpClient tcpClient;
        private DateTime lastReadTime, lastWriteTime;
        private NetworkStream networkStream;
        private CancellationTokenSource cancellationTokenSource;
        public event EventHandler SendMsgEvent; //使用默认的事件处理委托
        private Class_SQLiteOperator class_SQLiteOperator;
        private string Version;
        private bool ExitOk;
        private bool IsTabbedMdi { get { return barButtonItem25.Down; } }
        public float WaveMaxValue = 1563.0f;
        public float WaveMinValue = 1525.0f;
        /// <summary>
        /// 能量最小值
        /// </summary>
        public float PowerMinValue = -42;
        /// <summary>
        /// 能量最大值
        /// </summary>
        public float PowerMaxValue = -20;


        public void SocketClientStop(string message)
        {
            if (!cancellationTokenSource.IsCancellationRequested)
            {
                cancellationTokenSource.Cancel();
            }
            if (this.networkStream != null)
            {
                this.networkStream.Close();
                this.networkStream.Dispose();
                this.networkStream = null;
            }
            if (this.tcpClient != null)
            {
                this.tcpClient.Close();
                this.tcpClient.Dispose();
                this.tcpClient = null;
            }
            this.barButtonItem4.Caption = "开始获取远程数据";
            this.barButtonItem8.Enabled = false;
        }
        public void SocketServerDown(string ip, int port, string message)
        {
            SocketClientStop(string.Format("服务器{0}:{1}已下线！原因：{2}"
                , ip
                , port
                , message));
        }
        public void SocketClientNewMessage(byte[] vs)
        {
            if (Class_Tool.checkCRCByte(vs))
            {
                int point = 0;
                int address = vs[point++] & 0xff;//设备地址
                byte command = vs[point++];//命令代码
                if (command == 0x03)
                {
                    int length = vs[point++];//长度
                    if (length > 0)
                    {
                        int count = length / 6;//数据量
                        int channel = vs[point++] & 0xff;//通道
                        int index = 0;
                        byte[] waveIniByte = new byte[4];
                        byte[] powerIniByte = new byte[2];
                        float waveIni = 0;
                        short powerIni = 0;
                        float waveValue = 0;
                        float powerValue = 0;
                        IniEquipmentDateModel iniEquipmentDateModel = new IniEquipmentDateModel();
                        List<DataBatchModel> dataBatchModels = new List<DataBatchModel>(count);
                        while (index < count)
                        {
                            Buffer.BlockCopy(vs, point, waveIniByte, 0, 4);
                            point += 4;
                            Buffer.BlockCopy(vs, point, powerIniByte, 0, 2);
                            point += 2;
                            waveIni = Class_Tool.ByteArrayToFloat(waveIniByte);
                            powerIni = Class_Tool.ByteToShort(powerIniByte);
                            powerValue = float.Parse(powerIni.ToString()) / 50 - 70;
                            waveValue = waveIni + 1500;
                            if (powerValue > this.PowerMinValue
                                && powerValue < this.PowerMaxValue
                                && waveValue > this.WaveMinValue
                                && waveValue < this.WaveMaxValue)
                            {
                                dataBatchModels.Add(new DataBatchModel(waveValue, powerValue));
                            }
                            index++;
                        }
                        if (dataBatchModels.Count > 0)
                        {
                            iniEquipmentDateModel.address = address;
                            iniEquipmentDateModel.channel = channel;
                            iniEquipmentDateModel.dataBatchModels = dataBatchModels;
                            if (SendMsgEvent != null)
                            {
                                SendMsgEvent(this, iniEquipmentDateModel);
                            }
                            this.SetClientState(string.Format("设备{0}通道{1}得到{2}条数据"
                                , address
                                , channel + 1
                                , dataBatchModels.Count));
                        }
                        iniEquipmentDateModel.Clear();
                    }
                }
                if (command == 0x10)//注册
                {
                }
                if (command == 0x11)//退出
                {
                }
                if (command == 0x12)//在线状态
                {
                }
            }
            else
            {
                this.SetClientState("检验出错！");
            }

        }

        private void WriteMessage(string message)
        {
            WriteMessage(System.Text.Encoding.UTF8.GetBytes(message));
        }
        private void WriteMessage(byte[] vs)
        {
            try
            {
                if (ThreadPool.QueueUserWorkItem(new WaitCallback(SocketClientWrite)
                    , vs))
                {
                    this.SetClientState("命令发送成功!");
                }
            }
            catch (Exception error)
            {
                this.SetClientState(string.Format("命令发送错误异常：{0}", error.Message));
            }

        }
        private void SocketClientWrite(object message)
        {
            byte[] vs = message as byte[];
            SocketClientWrite(vs);
        }
        private void SocketClientWrite(byte[] vs)
        {
            if (vs != null && vs.Length > 0)
            {
                if (networkStream == null)
                    return;
                if (this.networkStream.CanWrite)
                {
                    try
                    {
                        this.networkStream.Write(vs, 0, vs.Length);
                        this.lastWriteTime = DateTime.Now;
                    }
                    catch (Exception Error)
                    {
                        throw Error;
                    }
                }
            }
        }
        private void ReadRun(object SocketClientParamModel)
        {
            SocketClientParamModel socketClientParamModel = SocketClientParamModel as SocketClientParamModel;
            while (!socketClientParamModel.cancellationTokenSource.IsCancellationRequested)
            {
                byte[] vs = new byte[125];
                int len;
                NetworkStream networkStream = socketClientParamModel.networkStream;
                try
                {
                    if (networkStream == null)
                    {
                        break;
                    }
                    if (networkStream != null && !socketClientParamModel.networkStream.CanRead)
                        continue;
                    if (networkStream != null)
                    {
                        len = socketClientParamModel.networkStream.Read(vs, 0, vs.Length);
                        if (len > 0)
                        {
                            if (vs.Length > 0)
                            {
                                this.lastReadTime = DateTime.Now;
                                if (len < vs.Length)
                                {
                                    byte[] target = new byte[len];
                                    Buffer.BlockCopy(vs, 0, target, 0, len);
                                    this.SocketClientNewMessage(target);
                                }
                                else
                                {
                                    this.SocketClientNewMessage(vs);
                                }
                            }
                        }
                        else
                        {
                            Thread.Sleep(200);
                            this.SocketServerDown(ip, port, "正常下线");
                            break;
                        }
                    }
                }
                catch (Exception error)
                {
                    this.SocketServerDown(ip, port, error.Message);
                    //throw error;
                }
            }
            this.SocketClientStop("读取线程下线！");
        }
        private void SetSocketClient()
        {
            this.tcpClient = new TcpClient();
            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_AllParamSetUp class_AllParamSetUp = new Class_AllParamSetUp();
            class_AllParamSetUp = class_PublicMethod.FromXmlToAllParamSetUpObject<Class_AllParamSetUp>("Class_AllParamSetUp");
            try
            {
                cancellationTokenSource = new CancellationTokenSource();
                cancellationTokenSource.Token.Register(() =>
                {
                    this.SetClientState("准备关闭线程!");
                });
                this.tcpClient.Connect(IPAddress.Parse(class_AllParamSetUp.Ip), class_AllParamSetUp.Port);
                this.ip = class_AllParamSetUp.Ip;
                this.port = class_AllParamSetUp.Port;
                this.tcpClient.SendTimeout = 1000;//设置发送操作成功完成的超时时间
                networkStream = this.tcpClient.GetStream();
                ThreadPool.SetMaxThreads(2, 2);
                ThreadPool.SetMinThreads(1, 1);

                if (ThreadPool.QueueUserWorkItem(new WaitCallback(ReadRun)
                    , new SocketClientParamModel(networkStream
                    , cancellationTokenSource
                    , this.tcpClient
                    , this)))
                {
                    this.barButtonItem4.Caption = "停止获取远程数据";
                    this.SetClientState("成功连接通讯服务器!");
                    this.displayOkMessage("成功连接通讯服务器!");
                }
                this.barButtonItem8.Enabled = true;
            }
            catch (Exception error)
            {
                this.tcpClient.Close();
                this.tcpClient.Dispose();
                throw error;
            }
        }
        private void InitTabbedMDI()
        {
            xtraTabbedMdiManager1.MdiParent = IsTabbedMdi ? this : null;
            barButtonItem38.Visibility = barButtonItem39.Visibility = barButtonItem40.Visibility = IsTabbedMdi ? BarItemVisibility.Never : BarItemVisibility.Always;
            this.barButtonItem25.Caption = IsTabbedMdi ? "标签方式" : "传统方式";
        }

        private void Ini(string SkinName)
        {
            this.repositoryItemProgressBar1.ShowTitle = true;
            this.barEditItem2.Visibility = BarItemVisibility.Never;
            ExitOk = false;
            Class_RibbonControl class_RibbonControl = new Class_RibbonControl();
            class_RibbonControl.SetRibbonControl(this.ribbonControl1);
            class_SQLiteOperator = new Class_SQLiteOperator();
            this.Text = class_SQLiteOperator.GetParam("A0002") + " V " + this.Version;
            string MdiSign = class_SQLiteOperator.GetParam("A0005");
            if (MdiSign != null && MdiSign.Equals("1"))
            {
                this.xtraTabbedMdiManager1.MdiParent = this;
                this.barButtonItem25.Down = true;
                this.barButtonItem38.Visibility = BarItemVisibility.Never;
                this.barButtonItem39.Visibility = BarItemVisibility.Never;
                this.barButtonItem40.Visibility = BarItemVisibility.Never;
            }
            else
            {
                this.xtraTabbedMdiManager1.MdiParent = null;
                this.barButtonItem25.Down = false;
                this.barButtonItem38.Visibility = BarItemVisibility.Always;
                this.barButtonItem39.Visibility = BarItemVisibility.Always;
                this.barButtonItem40.Visibility = BarItemVisibility.Always;
            }
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(SkinName);
            this.alertControl1.AllowHtmlText = true;
            this.alertControl1.ControlBoxPosition = DevExpress.XtraBars.Alerter.AlertFormControlBoxPosition.Top;
            this.alertControl1.FormLocation = DevExpress.XtraBars.Alerter.AlertFormLocation.BottomRight;
            displayState(string.Format("{0}，您好！", Class_Use.nickName));

            Class_NavBar class_NavBar = new Class_NavBar();
            class_NavBar.SetNavBarControlStyle(this.navBarControl1);

            SetNavBar();
            SetDockPanel();

            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_AllParamSetUp class_AllParamSetUp = new Class_AllParamSetUp();
            class_AllParamSetUp = class_PublicMethod.FromXmlToAllParamSetUpObject<Class_AllParamSetUp>("Class_AllParamSetUp");
            this.ip = class_AllParamSetUp.Ip;
            this.port = class_AllParamSetUp.Port;
            this.barButtonItem8.Enabled = false;
        }
        /// <summary>
        /// 显示状态栏
        /// </summary>
        /// <param name="content"></param>
        public void displayState(string content)
        {
            iDocName.Caption = content == null ? "" : content;
        }

        private void InitSkinGallery()
        {
        }
        private void SetDockPanel()
        {
            string DockIndex = class_SQLiteOperator.GetParam("A0001");

            if (DockIndex != null)
            {
                int index = int.Parse(DockIndex);
                switch (index)
                {
                    case 0:
                        this.dockPanel_win.Dock = DockingStyle.Float;
                        break;
                    case 1:
                        this.dockPanel_win.Dock = DockingStyle.Top;
                        break;
                    case 2:
                        this.dockPanel_win.Dock = DockingStyle.Bottom;
                        break;
                    case 3:
                        this.dockPanel_win.Dock = DockingStyle.Left;
                        break;
                    case 4:
                        this.dockPanel_win.Dock = DockingStyle.Right;
                        break;
                    default:
                        this.dockPanel_win.Dock = DockingStyle.Fill;
                        break;
                }
            }
        }
        private void SetNavBar()
        {
            this.navBarControl1.Items.Clear();
            this.navBarControl1.Groups.Clear();

            List<NavBarModel> navBarModels = class_SQLiteOperator.navBarModels(1, this.navBarControl1.Name);
            int groupIndex = 0;
            if (navBarModels != null && navBarModels.Count > 0)
            {
                NavBarGroup[] navBarGroups = new NavBarGroup[navBarModels.Count];
                NavBarItem[] navBarItems;
                foreach (NavBarModel itemGroup in navBarModels)
                {
                    NavBarGroup navBarGroup = new NavBarGroup();
                    navBarGroup.Tag = itemGroup.id;
                    navBarGroup.Name = itemGroup.id + "Group";
                    navBarGroup.Caption = itemGroup.caption;
                    navBarGroup.Expanded = true;
                    navBarGroup.SmallImageIndex = itemGroup.imageIndex + 300;
                    navBarGroup.Hint = itemGroup.hint;
                    navBarGroup.Appearance.Font = new System.Drawing.Font("Tahoma", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    navBarGroup.Appearance.Options.UseFont = true;
                    List<NavBarModel> navBarModelsItem = class_SQLiteOperator.navBarModels(2, itemGroup.id);
                    if (navBarModelsItem != null && navBarModelsItem.Count > 0)
                    {
                        NavBarItemLink[] navBarItemLinks = new NavBarItemLink[navBarModelsItem.Count];
                        navBarItems = new NavBarItem[navBarModelsItem.Count];
                        int itemIndex = 0;
                        foreach (NavBarModel item in navBarModelsItem)
                        {
                            NavBarItem navBarItem = new NavBarItem();
                            navBarItem.Tag = item.id;
                            navBarItem.Name = item.id + "NavBarItem";
                            navBarItem.Caption = item.caption;
                            navBarItem.SmallImageIndex = item.imageIndex;
                            navBarItem.Hint = item.hint;
                            navBarItem.Appearance.Font = new System.Drawing.Font("Tahoma", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                            navBarItem.Appearance.Options.UseFont = true;
                            navBarItem.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(navBarItems_LinkClicked);
                            navBarItems[itemIndex] = navBarItem;
                            navBarItemLinks[itemIndex++] = new NavBarItemLink(navBarItem);
                        }
                        navBarGroup.ItemLinks.AddRange(navBarItemLinks);
                        this.navBarControl1.Items.AddRange(navBarItems);
                    }
                    navBarGroups[groupIndex++] = navBarGroup;
                }
                this.navBarControl1.Groups.AddRange(navBarGroups);
                this.navBarControl1.ActiveGroup = navBarGroups[0];
            }

        }
        /// <summary>
        /// BarItem单击事件打开窗体
        /// </summary>
        /// <param name="sender">NaBarItem</param>
        /// <param name="e">NavBarLinkEventArgs</param>
        public void navBarItems_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            DevExpress.XtraNavBar.NavBarItem navBarItems = (DevExpress.XtraNavBar.NavBarItem)sender;
            OpenSubWindows(navBarItems.Caption, navBarItems.Tag);
            //MessageBox.Show(navBarItems.Tag.ToString());
        }

        private void SetDockStatic(DockVisibility dockVisibility)
        {
            if (this.dockPanel_win.Visibility != dockVisibility)
                this.dockPanel_win.Visibility = dockVisibility;
        }

        private void rgbiSkins_GalleryItemClick(object sender, GalleryItemClickEventArgs e)
        {
            string skinName = e.Item.Caption;
            if (skinName != null)
            {
                Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
                Class_AllParamSetUp class_AllParamSetUp = new Class_AllParamSetUp();
                class_AllParamSetUp = class_PublicMethod.FromXmlToAllParamSetUpObject<Class_AllParamSetUp>("Class_AllParamSetUp");
                class_AllParamSetUp.SkinName = skinName;
                if (class_PublicMethod.DataBaseAllParamSetUpValueToXml("Class_AllParamSetUp", class_AllParamSetUp))
                {
                    //setIniSkin(skinName);
                }
            }

        }

        private void iExit_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.Close();
        }

        private void Form_NewMain_Load(object sender, EventArgs e)
        {

        }

        #region 进度条
        public void SetProgressMax(int max)
        {
            this.repositoryItemProgressBar1.Minimum = 0;
            this.repositoryItemProgressBar1.Maximum = max;
            this.repositoryItemProgressBar1.Step = 1;
            this.barEditItem4.Visibility = BarItemVisibility.Always;
        }
        public void SetProgressOK()
        {
            this.barEditItem4.Visibility = BarItemVisibility.Never;
        }
        public void SetProgressPosition(int position)
        {
            this.barEditItem4.EditValue = position;
            Application.DoEvents();
        }
        #endregion

        private void SetClientState(string Text)
        {
            if (Text != null)
                this.SocketDisplayText.Caption = DateTime.Now.ToString("HH:mm:ss") + "：" + Text;
        }

        private void Form_NewMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            int index;
            switch (dockPanel_win.Dock)
            {
                case DockingStyle.Float:
                    index = 0;
                    break;
                case DockingStyle.Top:
                    index = 1;
                    break;
                case DockingStyle.Bottom:
                    index = 2;
                    break;
                case DockingStyle.Left:
                    index = 3;
                    break;
                case DockingStyle.Right:
                    index = 4;
                    break;
                default:
                    index = 5;
                    break;
            }
            class_SQLiteOperator.SetParam("A0001", index.ToString());
            if (this.xtraTabbedMdiManager1.MdiParent != null)
            {
                class_SQLiteOperator.SetParam("A0005", "1");
            }
            else
            {
                class_SQLiteOperator.SetParam("A0005", "0");
            }
        }
        private Form ActiveMDIForm
        {
            get { return this.ActiveMdiChild; }
        }

        private void Form_NewMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (ExitOk)
            {
                e.Cancel = false;
                return;
            }
            if (MessageBox.Show("您确定要退出此系统吗？", "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                if (this.tcpClient == null || this.tcpClient.Client == null || !this.tcpClient.Connected)
                {
                    WaitDialogForm waitDialogForm = new WaitDialogForm("正在保存当前状态......", "温馨提示");
                    List<Class_WindowType> class_WindowTypes = new List<Class_WindowType>();
                    foreach (XtraMdiTabPage xtra in xtraTabbedMdiManager1.Pages)
                    {
                        if (ActiveMDIForm.Tag != null)
                        {
                            Class_WindowType class_WindowType = new Class_WindowType();
                            class_WindowType = xtra.MdiChild.Tag as Class_WindowType;
                            if (class_WindowType != null)
                            {
                                if (class_WindowType.XmlFileName == (ActiveMDIForm.Tag as Class_WindowType).XmlFileName)
                                    class_WindowType.ActiveSign = true;
                                class_WindowTypes.Add(class_WindowType);
                            }
                        }
                    }
                    waitDialogForm.Close();
                    waitDialogForm.Dispose();
                    e.Cancel = false;
                }
                else
                {
                    MessageBox.Show("先关闭通讯后才能退出！", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    e.Cancel = true;
                }
            }
            else
                e.Cancel = true;
        }

        private void iAbout_ItemClick(object sender, ItemClickEventArgs e)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "http://" + class_SQLiteOperator.GetParam("A0004");
            process.StartInfo.Verb = "Open";
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            process.Start();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.timer1.Enabled = false;
            displayOkMessage(string.Format("{0}登录成功", Class_MyInfo.UseNameValue));
            OkRegistry(false);
        }
        /// <summary>
        /// 提示框方法
        /// </summary>
        /// <param name="caption"></param>
        /// <param name="textInfo"></param>
        /// <param name="hotTrackedText"></param>
        /// <param name="imageIndex"></param>
        private void displayAlertMessage(string caption, string textInfo, string hotTrackedText, int imageIndex)
        {
            caption = string.Format("<size=10><i>{0}</i>提示", caption);
            textInfo = string.Format("<size=12>{0}", textInfo);
            alertControl1.Show(
                this.FindForm(),
                caption,
                textInfo,
                hotTrackedText,
                this.imageCollection1.Images[imageIndex], null, true);
        }

        public void displayOkMessage(object textInfo)
        {
            displayAlertMessage("温馨", textInfo.ToString(), null, 68);
        }
        private void OkRegistry(bool IsDisplay)
        {
            string key = "asdrewv5";
            string registryCodeKey = "asdfasr2";
            Class_Net class_Net = new Class_Net();
            string message = class_Net.GetNetworkAdpaterID();
            Class_EncryptDes class_EncryptDes = new Class_EncryptDes();
            message = class_EncryptDes.DesEncrypt(message, key);

            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_RegistryModel class_RegistryModel = new Class_RegistryModel();
            class_RegistryModel = class_PublicMethod.FromXmlToRegistry<Class_RegistryModel>("OutFile");
            bool okSign = false;
            DateTime dateTime = DateTime.Now;
            Form_Registry form_Registry;
            if (class_RegistryModel != null)
            {
                if (class_RegistryModel.MachineCode.Equals(message))
                {
                    if (class_RegistryModel.RegistryCode != null)
                    {
                        string registryInfo = class_EncryptDes.DesDecrypt(class_RegistryModel.RegistryCode, registryCodeKey);
                        if (DateTime.TryParse(registryInfo, out dateTime))
                        {
                            if (dateTime >= DateTime.Now)
                            {
                                okSign = true;
                            }
                        }
                    }
                }
            }
            okSign = true;
            if (!IsDisplay && okSign)
            {
                return;
            }
            if (okSign)
                form_Registry = new Form_Registry(message, dateTime);
            else
                form_Registry = new Form_Registry(message);

            DialogResult dialogResult = form_Registry.ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                if (class_RegistryModel == null)
                {
                    class_RegistryModel = new Class_RegistryModel();
                }
                class_RegistryModel.MachineCode = message;
                class_RegistryModel.RegistryCode = form_Registry.GetRegistryCode();
                if (class_PublicMethod.RegistryCodeValueToXml("OutFile", class_RegistryModel))
                    MessageBox.Show("注册成功！", "温馨提示"
                    , MessageBoxButtons.OK
                    , MessageBoxIcon.Information
                    , MessageBoxDefaultButton.Button1);
            }
            if (dialogResult == DialogResult.Cancel)
            {
                if (!okSign)
                {
                    ExitOk = true;
                    this.Close();
                }
            }
            form_Registry.Dispose();

        }

        private void Form_NewMain_Shown(object sender, EventArgs e)
        {
            this.timer1.Enabled = true;
        }

        private void idNew_ItemClick(object sender, ItemClickEventArgs e)
        {
            openFirstPage();
        }
        private void RefreshForm(bool IsRefresh)
        {
            if (IsRefresh)
                Refresh();
        }

        private void openFirstPage()
        {
            OpenSubWindows(null, "welcome");
        }
        private void OpenSubWindows(string FormText, object Tag)
        {
            switch (Tag)
            {
                case "welcome":
                case "I0001":
                    Form_welCome form_WelCome = new Form_welCome(this);
                    form_WelCome.Tag = "welcome";
                    OpenSubForm(form_WelCome);
                    break;
                case "I0002":
                    break;
                case "I0003"://原始数据统计表
                    Form_ReportBase form_ReportBase = new Form_ReportBase(FormText, this);
                    form_ReportBase.Text = FormText;
                    form_ReportBase.Tag = Tag;
                    OpenSubForm(form_ReportBase);
                    break;
                case "I0004"://计算数据统计表
                    Form_EarthReport form_EarthReport = new Form_EarthReport(FormText, this);
                    form_EarthReport.Tag = Tag;
                    OpenSubForm(form_EarthReport);
                    break;
                case "I0005"://应变力统计表
                    break;
                case "I1006"://材料参数库
                    Form_strongPara form_StrongPara = new Form_strongPara(FormText);
                    form_StrongPara.Tag = Tag;
                    OpenSubForm(form_StrongPara);
                    break;
                case "I1007"://导入文件
                    Form_IntoTxt form_IntoTxt = new Form_IntoTxt(FormText, this);
                    form_IntoTxt.Tag = Tag;
                    OpenSubForm(form_IntoTxt);
                    break;
                case "I1009"://导入数据统计表
                    Form_EarthReportInPut form_EarthReportInPut = new Form_EarthReportInPut(FormText);
                    form_EarthReportInPut.Tag = Tag;
                    OpenSubForm(form_EarthReportInPut);
                    break;
                case "I0006":
                    Form_Eqiupment form_Eqiupment = new Form_Eqiupment(FormText);
                    form_Eqiupment.Tag = Tag;
                    OpenSubForm(form_Eqiupment);
                    break;
                case "I0023"://设备参数设置
                    Form_EquipmentParamer form_EquipmentParamer = new Form_EquipmentParamer(FormText);
                    form_EquipmentParamer.Tag = Tag;
                    OpenSubForm(form_EquipmentParamer);
                    break;
                case "I0007":
                    Form_Site form_Site = new Form_Site(FormText);
                    form_Site.Tag = Tag;
                    OpenSubForm(form_Site);
                    break;
                case "I0008":
                    break;
                case "I0009":
                    break;
                case "I0010":
                    break;
                case "I0011":
                    Form_Project form_Project = new Form_Project(FormText);
                    form_Project.Tag = Tag;
                    OpenSubForm(form_Project);
                    break;
                case "I0020":
                    Form_Project_test form_Project_Test = new Form_Project_test(FormText);
                    form_Project_Test.Tag = Tag;
                    OpenSubForm(form_Project_Test);
                    break;
                case "I0021":
                    Form_Project_picture form_Project_Picture = new Form_Project_picture(FormText);
                    form_Project_Picture.Tag = Tag;
                    OpenSubForm(form_Project_Picture);
                    break;
                case "I0012":
                case "I0013":
                case "I0014":
                    //Form_Force form_Force = new Form_Force(FormText);
                    //form_Force.Tag = Tag;
                    //OpenSubForm(form_Force);
                    break;
                case "I0017":
                case "I0018":
                    //Form_Formula form_Formula2 = new Form_Formula(FormText, 2);
                    //form_Formula2.Tag = Tag;
                    //OpenSubForm(form_Formula2);
                    break;
                case "I0019":
                    //Form_Formula form_Formula3 = new Form_Formula(FormText, 3);
                    //form_Formula3.Tag = Tag;
                    //OpenSubForm(form_Formula3);
                    break;
                case "I0015"://用户权限
                    Form_Use form_Use = new Form_Use(FormText);
                    form_Use.Tag = Tag;
                    OpenSubForm(form_Use);
                    break;
                case "I0016"://日志
                    Form_LogInfo form_LogInfo = new Form_LogInfo(FormText);
                    form_LogInfo.Tag = Tag;
                    OpenSubForm(form_LogInfo);
                    break;
                default:
                    break;
            }
        }
        private void OpenSubForm(Form OpenPage)
        {
            RefreshForm(true);
            bool finder = false;
            int num = -1;
            foreach (Form Children in this.MdiChildren)
            {
                num++;
                if (OpenPage.Tag == Children.Tag)
                {
                    finder = true;
                    Children.WindowState = FormWindowState.Maximized;
                    Children.Select();
                    Children.BringToFront();
                    if (this.xtraTabbedMdiManager1.MdiParent != null)
                    {
                        this.xtraTabbedMdiManager1.Pages[Children].TabControl.ViewInfo.SelectedTabPageIndex = num;
                    }
                    break;
                }
            }
            if (!finder)
            {
                WaitDialogForm waitDialogForm = new WaitDialogForm("正在玩命加载中......", "温馨提示");
                OpenPage.MdiParent = this;
                OpenPage.WindowState = FormWindowState.Maximized;
                OpenPage.Show();
                if (this.xtraTabbedMdiManager1.MdiParent != null)
                {
                    this.xtraTabbedMdiManager1.Pages[OpenPage].TabControl.ViewInfo.SelectedTabPageIndex = base.MdiChildren.Length - 1;
                }
                waitDialogForm.Close();
                waitDialogForm.Dispose();

            }

            RefreshForm(false);
        }
        private void enableCloseMenu(bool isEnable)
        {
            barButtonItem3.Enabled = isEnable;
            barButtonItem5.Enabled = isEnable;
            barButtonItem6.Enabled = isEnable;
        }

        private void xtraTabbedMdiManager1_MouseUp(object sender, MouseEventArgs e)
        {
            //点左键无效, 必须是点右键弹出菜单
            if (e.Button != MouseButtons.Right)
                return;
            BaseTabHitInfo hint = xtraTabbedMdiManager1.CalcHitInfo(e.Location);
            //点击有效,且点击在TabPage标题上
            if (hint.IsValid && (hint.Page != null))
            {
                //有效子窗体
                if (xtraTabbedMdiManager1.SelectedPage.MdiChild != null)
                {
                    Point p = xtraTabbedMdiManager1.SelectedPage.MdiChild.PointToScreen(e.Location);
                    enableCloseMenu(xtraTabbedMdiManager1.Pages.Count == 1 ? false : true);
                    this.popupMenu2.ShowPopup(p);
                }
            }
        }

        private void barButtonItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (ActiveMDIForm != null)
                ActiveMDIForm.Close();
        }

        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            foreach (Form Children in this.MdiChildren)
            {
                if (ActiveMDIForm != Children)
                {
                    Children.Close();
                }
            }
        }

        private void barButtonItem5_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<Form> list = new List<Form>();
            bool isRigth = false;
            foreach (XtraMdiTabPage xtra in xtraTabbedMdiManager1.Pages)
            {
                if (ActiveMDIForm == xtra.MdiChild)
                {
                    isRigth = true;
                    continue;
                }
                if (isRigth)
                {
                    list.Add(xtra.MdiChild);
                }
            }
            foreach (Form form in list)
            {
                xtraTabbedMdiManager1.Pages[form].MdiChild.Close();
            }
            list.Clear();
        }

        private void barButtonItem6_ItemClick(object sender, ItemClickEventArgs e)
        {
            List<Form> list = new List<Form>();
            bool isRigth = true;
            foreach (XtraMdiTabPage xtra in xtraTabbedMdiManager1.Pages)
            {
                if (ActiveMDIForm == xtra.MdiChild)
                {
                    isRigth = false;
                    break;
                }
                if (isRigth)
                {
                    list.Add(xtra.MdiChild);
                }
            }
            foreach (Form form in list)
            {
                xtraTabbedMdiManager1.Pages[form].MdiChild.Close();
            }
            list.Clear();

        }

        private void barButtonItem7_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (this.MdiChildren.Length == 0)
                return;
            if (MessageBox.Show(string.Format("您确定要关闭当前【{0}】个子窗体吗？", this.MdiChildren.Length.ToString()), "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                while (this.MdiChildren.Length > 0)
                {
                    this.MdiChildren[0].Close();
                }
            }
        }

        private void barButtonItem9_ItemClick(object sender, ItemClickEventArgs e)
        {
            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_AllParamSetUp class_AllParamSetUp = new Class_AllParamSetUp();
            class_AllParamSetUp = class_PublicMethod.FromXmlToAllParamSetUpObject<Class_AllParamSetUp>("Class_AllParamSetUp");

            string url = class_AllParamSetUp.AllPackageName;
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            if (!url.Contains("http"))
            {
                url = "http://" + url;
            }
            process.StartInfo.FileName = url;
            process.StartInfo.Verb = "Open";
            process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            process.Start();
        }

        private void barButtonItem10_ItemClick(object sender, ItemClickEventArgs e)
        {
            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Font font = new Font("Tahoma", class_PublicMethod.GetGridFontSize());
            FontDialog fontDialog = new FontDialog
            {
                Font = font
            };
            if (fontDialog.ShowDialog() == DialogResult.OK)
            {
                class_PublicMethod.SetGridFontSize(fontDialog.Font.Size);
            }
            fontDialog.Dispose();

        }
        /// <summary>
        /// 综合设置
        /// </summary>
        private void _AllSetUp()
        {
            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_AllParamSetUp class_AllParamSetUp = new Class_AllParamSetUp();
            class_AllParamSetUp = class_PublicMethod.FromXmlToAllParamSetUpObject<Class_AllParamSetUp>("Class_AllParamSetUp");
            Form_AllSetUp form_AllSetUp = new Form_AllSetUp(class_AllParamSetUp);
            if (form_AllSetUp.ShowDialog() == DialogResult.OK)
            {
                if (class_PublicMethod.DataBaseAllParamSetUpValueToXml("Class_AllParamSetUp", form_AllSetUp.class_AllParamSetUp))
                    MessageBox.Show("已将参数默认值，保存到本地!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            form_AllSetUp.Dispose();
        }

        private void iCopy_ItemClick(object sender, ItemClickEventArgs e)
        {
            _AllSetUp();
        }

        private void iCut_ItemClick(object sender, ItemClickEventArgs e)
        {
            Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
            Class_DataBaseConDefault class_DataBaseConDefault = new Class_DataBaseConDefault();
            class_DataBaseConDefault = class_PublicMethod.FromXmlToDefaultValueObject<Class_DataBaseConDefault>("DataBaseDefaultValues");
            Form_DataBaseDefaultSet form_DataBaseDefaultSet = new Form_DataBaseDefaultSet(class_DataBaseConDefault);
            if (form_DataBaseDefaultSet.ShowDialog() == DialogResult.OK)
            {
                if (class_PublicMethod.DataBaseDefaultValueToXml("DataBaseDefaultValues", form_DataBaseDefaultSet.class_DataBaseConDefault))
                    MessageBox.Show("已将数据库连接默认值，保存到本地!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
            form_DataBaseDefaultSet.Dispose();
        }

        private void iLargeUndo_ItemClick(object sender, ItemClickEventArgs e)
        {
            Form_UpdatePass form_UpdatePass = new Form_UpdatePass();
            if (form_UpdatePass.ShowDialog() == DialogResult.OK)
            {
                string Sql = string.Format(@"Update sys_useinfo
                    Set passWord='{1}' Where id='{0}'"
                    , Class_Use.id, form_UpdatePass.PassWord);
                Class_PublicMethod class_PublicMethod = new Class_PublicMethod();
                Class_DataBaseConDefault class_DataBaseConDefault = new Class_DataBaseConDefault();
                class_DataBaseConDefault = class_PublicMethod.FromXmlToDefaultValueObject<Class_DataBaseConDefault>("DataBaseDefaultValues");

                Class_MySqlDataBase class_MySqlDataBase = new Class_MySqlDataBase(class_DataBaseConDefault.dataSourceUrl
                    , class_DataBaseConDefault.dataBaseName
                    , class_DataBaseConDefault.dataSourceUserName
                    , class_DataBaseConDefault.dataSourcePassWord
                    , class_DataBaseConDefault.Port);
                if (class_MySqlDataBase.ExecuteSql(Sql) == 1)
                    MessageBox.Show("密码修改成功！", "温馨提示"
                        , MessageBoxButtons.OK
                        , MessageBoxIcon.Information
                        , MessageBoxDefaultButton.Button1);
                else
                    MessageBox.Show("密码修改失败！", "温馨提示"
                    , MessageBoxButtons.OK
                    , MessageBoxIcon.Error
                    , MessageBoxDefaultButton.Button1);
                class_MySqlDataBase.CloseSqlConnection();
            }
            form_UpdatePass.Dispose();
        }

        private void iSelectAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            //重置导航栏
            WaitDialogForm waitDialogForm = new WaitDialogForm("正在玩命加载中......", "温馨提示");
            SetNavBar();
            waitDialogForm.Close();
            waitDialogForm.Dispose();
        }

        private void barButtonItem14_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (this.MdiChildren.Length == 0)
                return;
            if (MessageBox.Show(string.Format("您确定要关闭当前【{0}】个子窗体吗？", this.MdiChildren.Length.ToString()), "温馨提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1) == DialogResult.OK)
            {
                while (this.MdiChildren.Length > 0)
                {
                    this.MdiChildren[0].Close();
                }
            }
        }

        private void iWeb_ItemClick(object sender, ItemClickEventArgs e)
        {
            OkRegistry(true);
        }

        private void barButtonItem18_ItemClick(object sender, ItemClickEventArgs e)
        {
            string fileName = Application.StartupPath + "\\" + class_SQLiteOperator.GetParam("A0003");
            if (File.Exists(fileName))
                System.Diagnostics.Process.Start(@fileName);
            else
                MessageBox.Show("文件“" + fileName + "”不存在，请与系统管理员联系！！", "温馨提示"
                , MessageBoxButtons.OK
                , MessageBoxIcon.Error
                , MessageBoxDefaultButton.Button1);
        }

        private void barButtonItem11_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetDockStatic(DockVisibility.Visible);
        }

        private void barButtonItem12_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetDockStatic(DockVisibility.Hidden);
        }

        private void barButtonItem13_ItemClick(object sender, ItemClickEventArgs e)
        {
            SetDockStatic(DockVisibility.AutoHide);
        }

        private void barToggleSwitchItem1_CheckedChanged(object sender, ItemClickEventArgs e)
        {
        }

        private void barButtonItem25_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.xtraTabbedMdiManager1.MdiParent = IsTabbedMdi ? this : null;
            this.barButtonItem25.Caption = IsTabbedMdi ? "标签方式" : "传统方式";
            this.barButtonItem25.ImageOptions.LargeImageIndex = IsTabbedMdi ? 66 : 67;
            if (IsTabbedMdi)
            {
                this.barButtonItem38.Visibility = BarItemVisibility.Never;
                this.barButtonItem39.Visibility = BarItemVisibility.Never;
                this.barButtonItem40.Visibility = BarItemVisibility.Never;
            }
            else
            {
                this.barButtonItem38.Visibility = BarItemVisibility.Always;
                this.barButtonItem39.Visibility = BarItemVisibility.Always;
                this.barButtonItem40.Visibility = BarItemVisibility.Always;
            }
        }

        private void barButtonItem38_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }

        private void barButtonItem39_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }

        private void barButtonItem40_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void barButtonItem41_ItemClick(object sender, ItemClickEventArgs e)
        {
            displayOkMessage(string.Format("{0}登录成功", Class_MyInfo.UseNameValue));
        }

        private void barButtonItem8_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (this.tcpClient != null && this.tcpClient.Connected)
            {
                try
                {
                    WriteMessage(Class_Tool.GetLineCommand());
                }
                catch (Exception error)
                {
                    this.SetClientState(string.Format("通讯连接错误异常：{0}", error.Message));
                }
            }
        }

        private void barButtonItem4_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (this.tcpClient == null || this.tcpClient.Client == null || !this.tcpClient.Connected)
            {
                try
                {
                    SetSocketClient();
                    Thread.Sleep(500);
                    WriteMessage(Class_Tool.GetRegisterCommand());
                }
                catch (Exception error)
                {
                    this.SetClientState(string.Format("通讯连接错误异常：{0}", error.Message));
                }
            }
            else
            {
                if (!cancellationTokenSource.IsCancellationRequested)
                {
                    cancellationTokenSource.Cancel();
                    WriteMessage(Class_Tool.GetExitCommand());
                }
            }
        }

    }
}
